package com.assic.utils.db.file;

import java.io.File;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.nutz.lang.Files;

/**
 * @author Ixion
 * 
 */
public class DBFileReader {
	private static Connection conn;
	private static Statement statement;
	private static String tableName = "IOFD_FILE";

	/**
	 * 获取数据库连接并初始化statemrent
	 */
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Properties properties = new Properties();
			properties.load(DBFileWriter.class.getClassLoader()
					.getResourceAsStream("config/dataSource.properties"));
			conn = DriverManager.getConnection(
					properties.getProperty("db-url"),
					properties.getProperty("db-username"),
					properties.getProperty("db-password"));
			conn.setAutoCommit(false);// 禁止自动提交
			statement = conn.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static File readFileFromDB(String fileName, String fileType) {
		File file = null;
		try {
			String SELECT = "SELECT * FROM " + tableName
					+ " WHERE FILE_NAME = '" + fileName + "' AND FILE_TYPE = '"
					+ fileType + "'";// 数据查询语句
			ResultSet rs = statement.executeQuery(SELECT);
			if (rs.next()) {
				file = new File(rs.getString("FILE_NAME") + "."
						+ rs.getString("FILE_TYPE"));
				Blob b = rs.getBlob("FILE_DATA");
				byte[] data = b.getBytes(1, (int) b.length());
				Files.write(file, data);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return file;
	}
}
